import 'package:flutter/material.dart';
import 'package:flutter_shop/routers/details_router.dart';
import 'package:flutter_shop/routers/fluro_navigator.dart';
import '../service/service_method.dart';
import 'dart:convert';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  _homePageState createState() => _homePageState();
}

class _homePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  int page = 1;
  List<Map> hotGoodList = new List();
  GlobalKey <RefreshFooterState> _globalKey=new GlobalKey<RefreshFooterState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var formData = {'lon': '115.02932', 'lat': '35.76189'};

    return Scaffold(
      backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
      appBar: AppBar(
        title: Text('百姓生活+'),
      ),
      body: FutureBuilder(
        future: request('homePageContext', formData: formData),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var data = json.decode(snapshot.data.toString());
            List<Map> swiperDataList =
                (data['data']['slides'] as List).cast(); // 顶部轮播组件数

            List<Map> navigatorList = (data['data']['category'] as List).cast();

            String adpictureList =
                data['data']['advertesPicture']['PICTURE_ADDRESS'];

            String leaderImage = data['data']['shopInfo']['leaderImage'];
            String leaderPhone = data['data']['shopInfo']['leaderPhone'];

            List<Map> recommentList =
                (data['data']['recommend'] as List).cast();
            String floor1Title = data['data']['floor1Pic']['PICTURE_ADDRESS'];
            String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS'];
            String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS'];

            List<Map> floor1 = (data['data']['floor1'] as List).cast();

            List<Map> floor2 = (data['data']['floor2'] as List).cast();

            List<Map> floor3 = (data['data']['floor3'] as List).cast();

            return EasyRefresh(
              refreshFooter: ClassicsFooter(
                bgColor: Colors.white,
                key: _globalKey,
                textColor: Colors.pink,
                moreInfoColor: Colors.pink,
                showMore: true,
                noMoreText: '',
                moreInfo: '加载中...',
                loadReadyText: '上拉加载更多',
              ),
              child: ListView(
                children: <Widget>[
                  SwiperDiy(swiperDataList: swiperDataList),
                  TopNavigator(
                    navigatorList: navigatorList,
                  ),
                  AdBanner(
                    adpicture: adpictureList,
                  ),
                  LeaderPhone(
                    imagePath: leaderImage,
                    phone: leaderPhone,
                  ),
                  Recommend(
                    recommendList: recommentList,
                  ),
                  FloorTitle(
                    floorPath: floor1Title,
                  ),
                  FloorContent(
                    floorGoodsList: floor1,
                  ),
                  FloorTitle(
                    floorPath: floor2Title,
                  ),
                  FloorContent(
                    floorGoodsList: floor2,
                  ),
                  FloorTitle(
                    floorPath: floor3Title,
                  ),
                  FloorContent(
                    floorGoodsList: floor3,
                  ),
                  getHotGoodWidgetList(),
                ],
              ),
              loadMore: () async {
                var formData = {'page': page};
                await request('homePageBelowConten', formData: formData)
                    .then((data) {
                  var val = json.decode(data);
                  List<Map> newHotGoodList = (val['data'] as List).cast();

                  setState(() {
                    hotGoodList.addAll(newHotGoodList);
                  });
                  page++;
                });
              },
            );
          } else {
            return Center(
              child: Text('加载中。。。'),
            );
          }
        },
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  //火爆专区组件组合
  Widget getHotGoodWidgetList() {
    return Column(
      children: <Widget>[
        _hotGoodTitle(),
        _wrapList(),
      ],
    );
  }

//火爆赚取标题
  Widget _hotGoodTitle() {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.all(5.0),
      child: Text(
        '火爆专区',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //火爆专区布局
  Widget _wrapList() {
    if (hotGoodList.length > 0) {
      List<Widget> wapList = hotGoodList.map((map) {
        return InkWell(
          onTap: () {
            NavigatorUtils.push(context, '${DatailsRouter.detailsPage}?goodsId=${map['goodsId']}',
                replace: false);
          },
          child: Container(
            margin: EdgeInsets.only(bottom: 3.0),
            padding: EdgeInsets.all(5.0),
            color: Colors.white,
            width: ScreenUtil().setWidth(372),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.network(
                  map['image'],
                  width: ScreenUtil().setWidth(370),
                ),
                Text(
                  map['name'],
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text('￥${map['mallPrice']}'),
                    SizedBox(
                      width: ScreenUtil().setWidth(20.0),
                    ),
                    Text(
                      '￥${map['price']}',
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2, //一行显示几个
        children: wapList,
      );
    } else {
      return Text('暂无火爆商品...');
    }
  }
}

///轮播图
class SwiperDiy extends StatelessWidget {
  final List swiperDataList;

  SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      width: ScreenUtil().setHeight(750),
      height: ScreenUtil().setHeight(333),
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return InkWell(
            onTap: () {
              NavigatorUtils.push(context, '${DatailsRouter.detailsPage}?goodsId=${swiperDataList[index]['goodsId']}',
                  replace: false);
            },
            child: Image.network(
              '${swiperDataList[index]['image']}',
              fit: BoxFit.fill,
            ),
          );
        },
        itemCount: swiperDataList.length,
        pagination: new SwiperPagination(),
        /*是都有指示器*/
        autoplay: true, //是否自动轮播
      ),
    );
  }
}

///itemMenu
class TopNavigator extends StatelessWidget {
  final List navigatorList;

  TopNavigator({Key key, this.navigatorList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if (navigatorList.length > 10) {
      navigatorList.length = 10;
    }
    return Container(
      color: Colors.white,
      height: ScreenUtil().setHeight(320),
      padding: EdgeInsets.all(3.0),
      margin: EdgeInsets.only(top: 5.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),//不可滑动
        crossAxisCount: 5,
        children: navigatorList.map((item) {
          return _gridViewItemUI(context, item);
        }).toList(),
      ),
    );
  }

  Widget _gridViewItemUI(BuildContext context, item) {
    return InkWell(
      onTap: () {
        NavigatorUtils.push(context, '${DatailsRouter.detailsPage}?goodsId=${item['goodsId']}',
            replace: false);
      },
      child: Column(
        children: <Widget>[
          Image.network(
            item['image'],
            width: ScreenUtil().setWidth(95),
          ),
          Text(item['mallCategoryName']),
        ],
      ),
    );
  }
}

///广告点击拨打电话
class AdBanner extends StatelessWidget {
  final String adpicture;

  AdBanner({Key key, this.adpicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Image.network(adpicture),
    );
  }
}

///推荐拨打电话
class LeaderPhone extends StatelessWidget {
  String imagePath;
  String phone;

  LeaderPhone({Key key, this.imagePath, this.phone});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: InkWell(
        onTap: () {
          _launchUrl();
        },
        child: Container(
          child: Image.network(imagePath),
        ),
      ),
    );
  }

  void _launchUrl() async {
    String url = 'tel:' + phone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw '不能拨打电话';
    }
  }
}

///商品推荐
class Recommend extends StatelessWidget {
  final recommendList;

  Recommend({Key key, this.recommendList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      height: ScreenUtil().setWidth(400),
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[_titleWidet(), _recommendList()],
      ),
    );
  }

  //标题组件
  Widget _titleWidet() {
    return Container(
      height: ScreenUtil().setHeight(50.0),
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(color: Colors.black12, width: 0.5))),
      child: Text(
        '推荐商品',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //item组件
  Widget _listItem(BuildContext context,index) {
    return InkWell(
      onTap: (){
        NavigatorUtils.push(context, '${DatailsRouter.detailsPage}?goodsId=${recommendList[index]['goodsId']}',
            replace: false);
      },
      child: Container(
        padding: EdgeInsets.all(8.0),
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(right: BorderSide(color: Colors.black12, width: 0.5))),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('￥${recommendList[index]['mallPrice']}'),
            Text(
              '￥${recommendList[index]['price']}',
              style: TextStyle(
                  decoration: TextDecoration.lineThrough, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  //横向列表Widget
  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setWidth(330),
      child: ListView.builder(
        itemBuilder: (buildContext, index) {
          return _listItem(buildContext,index);
        },
        itemCount: recommendList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}

///路层标题
class FloorTitle extends StatelessWidget {
  String floorPath;

  FloorTitle({Key key, this.floorPath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(floorPath),
    );
  }
}

///路层商品列表
class FloorContent extends StatelessWidget {
  List floorGoodsList;

  FloorContent({Key key, this.floorGoodsList});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Column(
        children: <Widget>[
          _firstRow(context),
          _otherGoods(context),
        ],
      ),
    );
  }

  Widget _goodsItem(Map goods,BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        child: Image.network(goods['image']),
        onTap: () {

          NavigatorUtils.push(context, '${DatailsRouter.detailsPage}?goodsId=${goods['goodsId']}',
              replace: false);
        },
      ),
    );
  }

  Widget _firstRow(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          _goodsItem(floorGoodsList[0],context),
          Column(
            children: <Widget>[
              _goodsItem(floorGoodsList[1],context),
              _goodsItem(floorGoodsList[2],context),
            ],
          )
        ],
      ),
    );
  }

  Widget _otherGoods(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          _goodsItem(floorGoodsList[3],context),
          _goodsItem(floorGoodsList[4],context)
        ],
      ),
    );
  }
}
